<template>
  <table class="user-table">
    <colgroup>
      <col style="width:60px;">     <!-- 1. 编号 -->
      <col style="width:100px;">    <!-- 2. 用户名 -->
      <col style="width:100px;">    <!-- 3. 密码 -->
      <col style="width:120px;">    <!-- ★ 权限 -->
      <col style="width:160px;">    <!-- 4. 上次登录时间 -->
      <col style="width:250px;">    <!-- 5. 上次登录 IP -->
      <col style="width:250px;">    <!-- 6. 最近操作 -->
      <col class="manage-col">      <!-- 7. 管理：不给宽度，吃剩余 -->
    </colgroup>

    <thead>
    <tr class="head-row">
      <th>编号</th>
      <th>用户名</th>
      <th>密码</th>
      <th>权限</th>           <!-- ★ --->
      <th>上次登录时间</th>
      <th>上次登录 IP</th>
      <th>最近操作</th>
      <th class="manage-col">管理</th>
    </tr>
    </thead>

    <tbody>
    <tr v-for="user in users" :key="user.id" :data-id="user.id">
      <td>{{ user.id }}</td>
      <td>{{ user.username }}</td>
      <td>*******</td>
      <td>{{ ROLE_MAP[user.role] ?? user.role }}</td>
      <td>{{ user.last_login_time ?? '-' }}</td>
      <td>{{ user.last_login_ip ?? '-' }}</td>
      <td>{{ user.last_operation ?? '-' }}</td>
      <td class="manage-col">
        <a class="link-delete" @click="deleteUser(user.id, user.username)">删除</a>
        <span>&nbsp;&nbsp;</span>
        <el-dropdown>
          <a class="link-role">权限</a>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                  :disabled="user.role === 'super'"
                  @click="changeUserRole(user, '超级管理员')">
                超级管理员
              </el-dropdown-item>
              <el-dropdown-item
                  :disabled="user.role === 'staff'"
                  @click="changeUserRole(user, '保洁人员')">
                保洁人员
              </el-dropdown-item>
              <el-dropdown-item
                  :disabled="user.role === 'normal'"
                  @click="changeUserRole(user, '普通用户')">
                普通用户
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </td>
    </tr>
    </tbody>
  </table>

  <div class="user-actions">
    <button class="btn-create" @click="modalVisible = true">新增</button>
  </div>

  <!-- ========== 新增用户 · 弹窗 ========== -->
  <div v-if="modalVisible" class="modal-mask">
    <div class="modal">
      <div class="modal-header">
        <span class="modal-title">新增用户</span>
        <button class="modal-close" @click="modalVisible = false">×</button>
      </div>

      <div class="modal-body">
        <div class="modal-field">
          <label>用户名</label>
          <input v-model="newUserForm.username" type="text" id="new-username" placeholder="请输入用户名">
        </div>
        <div class="modal-field">
          <label>密码</label>
          <input v-model="newUserForm.password" type="password" id="new-password" placeholder="请输入密码">
        </div>
        <div class="modal-field">
          <label>角色</label>
          <select v-model="newUserForm.role" id="new-role">
            <option value="super">超级管理员</option>
            <option value="staff">保洁人员</option>
            <option value="normal" selected>普通用户</option>
          </select>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn-cancel modal-close" @click="modalVisible = false">取消</button>
        <button class="btn-save" @click="createUser">保存</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'

/* ======================================================== 公共工具 ==================================================================== */
const ROLE_MAP = {
  super: '超级管理员',
  staff: '保洁人员',
  normal: '普通用户'
}

const API_BASE = '/api/v1'
const TOKEN = localStorage.getItem('token')

async function api(url, opt = {}) {
  return fetch(`${API_BASE}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${TOKEN}`,
      ...(opt.headers || {})
    },
    ...opt
  }).then(r => r.json())
}

function toast(msg) {
  alert(msg) // 简易提示，可替换成自定义弹框
}

// 用户管理数据
const users = ref([])

/* 1. 数据加载 & 渲染 */
const loadUsers = async (page = 1, limit = 10) => {
  if (!TOKEN) {
    toast('登录信息失效，请重新登录')
    // 这里应该跳转到登录页面
    return
  }
  const res = await api(`/users?page=${page}&limit=${limit}`)
  if (res.code === 0) {
    users.value = res.data.users || []
  } else {
    toast(res.message || '获取用户失败')
  }
}

/* 删除用户 */
const deleteUser = async (id, username) => {
  ElMessageBox.confirm(
      `确定删除用户 ${username} 吗？`,
      '提示',
      {type: 'warning'}
  ).then(async () => {
    const d = await api(`/users/${id}`, {method: 'DELETE'})
    if (d.code === 0) {
      toast('删除成功')
      users.value = users.value.filter(u => u.id !== id)
    } else {
      toast(d.message)
    }
  }).catch(() => {
    // 用户点击取消
  })
}

/* 修改用户角色 */
const changeUserRole = async (user, roleText) => {
  const d = await api(`/users/${user.id}`, {
    method: 'PUT',
    body: JSON.stringify({
      username: user.username,
      password: user.username, // 规则：密码 = 用户名
      role: roleText
    })
  })

  if (d.code === 0) {
    user.role = roleText
    toast('角色已修改')
  } else {
    toast(d.message)
  }
}

// 新增用户表单数据
const newUserForm = reactive({
  username: '',
  password: '',
  role: 'normal'
})

const modalVisible = ref(false)

/* 新增用户 */
const createUser = async () => {
  const {username, password, role} = newUserForm
  if (!username || !password) {
    toast('请填写用户名和密码')
    return
  }

  const d = await api('/users', {
    method: 'POST',
    body: JSON.stringify({username, password, role})
  })

  if (d.code === 0) {
    toast('新增用户成功')
    modalVisible.value = false
    users.value.unshift(d.data)
    // 清空表单
    newUserForm.username = ''
    newUserForm.password = ''
    newUserForm.role = 'normal'
  } else {
    toast(d.message)
  }
}

onMounted(() => {
  loadUsers()
})

// 暴露方法给父组件
defineExpose({
  loadUsers
})
</script>

<style scoped>
/* 从 control.css 中提取相关样式 */
.user-table {
  width: 70%;
  border-collapse: collapse;
  margin: 0 auto; /*表格整体居中 */
  table-layout: fixed;
}

/* 表头行字体样式 */
.user-table .head-row th {
  font-size: 16px;
  font-weight: 500;
  color: #898989;
  letter-spacing: 0.5px;
}

.user-table th,
.user-table td {
  padding: 18px 4px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
}

.user-table th {
  color: #666;
  font-weight: 500;
}

.user-table .manage-col {
  padding-left: 0px !important;
  padding-right: 12px !important;
}

/* 操作链接 */
.link-delete,
.link-role {
  color: #1890ff;
  text-decoration: none; /* 去下划线 */
  cursor: pointer;
}

/* ===== “新增”按钮居中 ===== */
.user-actions {
  margin-top: 28px;
  text-align: center;
}

.btn-create {
  padding: 8px 40px;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.btn-create:hover {
  opacity: .85;
}

/* ============================= 弹窗======================================== */

/* ===== Modal 基础遮罩 ===== */
.modal-mask {
  position: fixed;
  inset: 0; /* top/right/bottom/left:0 */
  background: rgba(0, 0, 0, .45); /* 半透明黑 */
  display: flex; /* 默认显示 */
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

/* ===== Modal 容器 ===== */
.modal {
  width: 480px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, .1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* Header */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  line-height: 1;
  cursor: pointer;
  color: #999;
}

.modal-close:hover {
  color: #1890ff;
}

/* Body */
.modal-body {
  padding: 24px;
}

.modal-field {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}

.modal-field label {
  width: 70px;
  font-size: 16px;
  color: #333;
}

.modal-field input,
.modal-field select {
  flex: 1;
  height: 38px;
  padding: 0 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

/* Footer */
.modal-footer {
  display: flex;
  justify-content: center; /* ← 原来是 flex-end */
  gap: 24px; /* 两按钮间距保持不变 */
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.modal-footer .btn-cancel {
  width: 120px;
  height: 38px;
  background: #fff;
  color: #666;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.modal-footer .btn-save {
  width: 160px;
  height: 38px;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}

.modal-footer .btn-save:hover,
.modal-footer .btn-cancel:hover {
  opacity: .85;
}
</style>